package cn.edu.hqu.wel.shiyan1.controller;

import cn.edu.hqu.wel.shiyan1.model.Movie;
import cn.edu.hqu.wel.shiyan1.service.MovieService;
import cn.edu.hqu.wel.shiyan1.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/movies")
public class MovieController {

    @Autowired
    private MovieService movieService;
    @Autowired
    private FileStorageService fileStorageService;

    @GetMapping
    public ResponseEntity<List<Movie>> getAllMovies() {
        List<Movie> movies = movieService.getAllMovies();
        return ResponseEntity.ok(movies);
    }

    @PostMapping(value = "/uploadPoster/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadPoster(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        String fileName = fileStorageService.storeFile(file);
        if (fileName != null) {
            Movie movie = movieService.getMovieById(id).orElse(null);
            if (movie != null) {
                movie.setPosterUrl("/api/movies/posters/" + fileName);
                movieService.updateMovie(movie);
                return ResponseEntity.ok("Poster uploaded successfully. URL: " + movie.getPosterUrl());
            } else {
                return ResponseEntity.notFound().build();
            }
        } else {
            return ResponseEntity.badRequest().body("Failed to upload poster");
        }
    }

    @GetMapping("/posters/{filename:.+}")
    public ResponseEntity<Resource> downloadPoster(@PathVariable String filename) throws IOException {
        Path filePath = fileStorageService.getFileStorageLocation().resolve(filename).normalize();
        Resource resource = new org.springframework.core.io.UrlResource(filePath.toUri());
        if (resource.exists() || resource.isReadable()) {
            String contentType = Files.probeContentType(filePath);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, contentType)
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}